<template>
  <div class="container">
    <div class="inp_title page_title" style="margin-bottom: 20px">
      {{ saleTitle }}
    </div>
    <!-- 分销名称 -->
    <div class="flex_y_center" style="margin-bottom: 20px">
      <div class="inp_title">
        <span>*</span>
        分销名称：
      </div>
      <el-input
        v-model="saleForm.title"
        placeholder="请输入分销名称"
        style="width: 25%"
      />
    </div>
    <!-- 销售额计算周期 -->
    <div class="flex_y_center" style="margin-bottom: 20px">
      <div class="inp_title">
        <span>*</span>
        销售额计算周期：
      </div>
      <div>
        <el-radio-group v-model="saleForm.settle_cycle">
          <el-radio label="day">日</el-radio>
          <el-radio label="week">周</el-radio>
          <el-radio label="month">月</el-radio>
          <el-radio label="year">年</el-radio>
        </el-radio-group>
      </div>
    </div>
    <!-- 分销规则 -->
    <div style="margin-bottom: 20px">
      <div class="flex_y_center">
        <div class="inp_title">
          <span>*</span>
          分销规则：
        </div>
        <el-button type="primary" @click="addSaleRule">添加分销规则</el-button>
      </div>
      <div v-for="(item, index) of ladder" :key="index">
        <div class="flex_y_center" style="margin-top: 10px">
          <div class="inp_title"></div>
          <el-input
            v-model="item.threshold_amount"
            placeholder="请输入条件金额"
            style="width: 17%"
          >
            <template slot="append">元</template>
          </el-input>
          <el-select
            v-model="item.sale_strategy"
            placeholder="请选择提成方式"
            style="width: 15%"
            @change="item.sale_value = 0"
          >
            <el-option label="提成金额" value="amount" />
            <el-option label="提成比例" value="ratio" />
          </el-select>
          <el-input
            v-model="item.sale_value"
            max="1"
            min="0"
            placeholder="请输入提成"
            style="width: 15%; margin-right: 10px"
          >
            <template slot="append">
              {{ item.sale_strategy == 'amount' ? '元' : '%' }}
            </template>
          </el-input>
          <el-button type="text" @click="ladder.splice(index, 1)">
            删除
          </el-button>
        </div>
      </div>
    </div>
    <!-- 选择商品 -->
    <div style="display: flex; margin-bottom: 20px">
      <div class="inp_title" style="position: relative; top: 5px">
        <span>*</span>
        选择商品：
      </div>
      <div style="flex-grow: 1">
        <el-button type="primary" @click="getGoods">选择关联商品</el-button>
        <!-- 选中的商品列表 -->
        <el-table
          v-show="selGoodsList.length != 0"
          :data="selGoodsList"
          style="margin-top: 10px"
          title="关联商品"
        >
          <el-table-column label="商品名称" prop="goods_name" />
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button type="text" @click="delRow(scope.row, scope.$index)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <!-- 规则持续时间 -->
    <div style="display: flex">
      <div class="inp_title">
        <span>*</span>
        规则持续时间：
      </div>
      <div>
        <el-radio-group
          v-model="saleForm.expire_type"
          style="
            display: flex;
            flex-direction: column;
            justify-content: space-between;
          "
        >
          <el-radio label="range_at">时间段</el-radio>
          <el-radio label="long_at" style="margin: 15px 0">长期有效</el-radio>
        </el-radio-group>
      </div>
    </div>
    <!-- 有效期 -->
    <div
      v-if="saleForm.expire_type == 'range_at'"
      class="flex_y_center"
      style="margin-bottom: 20px"
    >
      <div class="inp_title">
        <span>*</span>
        有效期：
      </div>
      <el-date-picker
        v-model="saleForm.start_at"
        placeholder="选择活动开始日期"
        type="date"
        value-format="yyyy-MM-dd hh:mm"
      />
      <div style="margin: 0 5px">至</div>
      <el-date-picker
        v-model="saleForm.end_at"
        placeholder="选择活动结束日期"
        type="date"
        value-format="yyyy-MM-dd hh:mm"
      />
    </div>
    <div style="text-align: center">
      <el-button type="primary" @click="addSales">保存</el-button>
      <el-button @click="$emit('send')">返回</el-button>
    </div>

    <el-dialog title="选择关联商品" :visible.sync="goodsDialog">
      <el-table
        ref="goodsTable"
        :data="goodsList"
        @row-click="handleCurrentChange"
        @selection-change="selectCrouse"
      >
        <el-table-column type="selection" />
        <el-table-column label="商品名称" prop="goods_name" />
        <el-table-column label="商品规格" prop="goods_attr_name" />
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
  import { getGoodsList } from '@/api/public'
  import { addSale } from '@/api/distributor'

  export default {
    props: {
      oSaleInfo: {
        type: Object,
        default() {
          return {}
        },
      },
    },
    data() {
      return {
        saleTitle: '新增分销规则',
        goodsName: '', // 商品搜索关键字
        goodsList: [], // 存放获取的商品列表
        goodsDialog: false, // 商品对话框
        selGoodsList: [], // 存放选中的商品
        ladder: [], // 存放

        saleForm: {
          title: '', // 分销策略名称
          settle_cycle: 'month', // 计算周期类 day：日；week：周；month：月；year：年
          expire_type: '', // 策略周期 long_at：长期；range_at：区间
          start_at: '', // 开始时间（策略周期为区间必填）
          end_at: '', // 结束时间（策略周期为区间必填）
          strategy_item: [], // 分销商品数组
          strategy_ladder: [], // 分销规则设置数组
        },
      }
    },
    watch: {
      selGoodsList(newValue) {
        for (let item of newValue) {
          this.saleForm.strategy_item.push({
            goods_id: item.goods_id,
            attr_id: item.goods_attr_id || item.attr_id,
          })
        }
      },
      ladder: {
        deep: true,
        handler() {
          this.saleForm.strategy_ladder = this.ladder
        },
      },
      'saleForm.expire_type'(newValue) {
        if (newValue == 'long_at') {
          this.saleForm.start_at = ''
          this.saleForm.end_at = ''
        }
      },
    },
    created() {
      this.assignForm()
    },
    methods: {
      // 赋值
      assignForm() {
        if (JSON.stringify(this.oSaleInfo) != '{}') {
          this.saleTitle = '编辑分销规则'
          for (let item in this.saleForm) {
            if (item == 'strategy_item') {
              this.selGoodsList = this.oSaleInfo.item
            } else if (item == 'strategy_ladder') {
              this.ladder = this.oSaleInfo.ladder
            } else {
              this.saleForm[item] = this.oSaleInfo[item]
            }
          }
          this.saleForm.strategy_id = this.oSaleInfo.id
        }
      },

      // 获取商品列表
      getGoods() {
        if (this.goodsList.length == 0) {
          const data = {
            goods_name: this.goodsName,
            goods_type: 'all',
            type: 'strategy',
          }
          getGoodsList(data).then((res) => {
            this.goodsList = []
            // 将可选择商品筛选出来
            for (let item of res.data) {
              if (
                item.type_code != 'curriculum' &&
                item.type_code != 'service'
              ) {
                this.goodsList.push(item)
              }
            }
            this.goodsDialog = true
            // 延迟到js执行完成并dom更新执行
            this.$nextTick(() => {
              // 判断是都有选择商品
              if (this.selGoodsList.length != 0) {
                for (let item of this.selGoodsList) {
                  for (let itemChild of this.goodsList) {
                    if (item.goods_id == itemChild.goods_id) {
                      this.$refs.goodsTable.toggleRowSelection(itemChild, true)
                    }
                  }
                }
              }
            })
          })
        } else {
          this.goodsDialog = true
        }
      },
      // 添加分销规则
      addSaleRule() {
        this.ladder.push({
          threshold_amount: '',
          sale_strategy: '',
          sale_value: 0,
        })
      },

      // 选择表格展示商品
      selectCrouse(select) {
        this.selGoodsList = select
      },
      // 让选中的行勾选
      handleCurrentChange(row) {
        let bool = true
        for (let item of this.selGoodsList) {
          if (item.goods_id == row.goods_id) {
            bool = false
            break
          }
        }
        this.$refs.goodsTable.toggleRowSelection(row, bool)
      },
      // 删除商品表格行
      delRow(row, index) {
        this.selGoodsList.splice(index, 1)
        if (this.goodsList.length != 0) {
          this.$refs.goodsTable.toggleRowSelection(row, false)
        }
      },

      // 添加分销
      addSales() {
        const params = this.saleForm
        if (typeof params.strategy_item != 'string') {
          params.strategy_item = JSON.stringify(params.strategy_item)
        }
        if (typeof params.strategy_ladder != 'string') {
          params.strategy_ladder = JSON.stringify(params.strategy_ladder)
        }
        addSale(params).then(() => {
          this.$emit('send')
        })
      },
    },
  }
</script>

<style scoped>
  span {
    color: red;
  }

  .page_title {
    font-size: 18px;
    font-weight: 600;
  }
  .inp_title {
    width: 140px;
    text-align: right;
  }
</style>
